package com.wisdom.benefit.jufa.utils;

import android.app.Activity;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Activity管理类
 * Created by zhoudawei on 2017/7/21.
 */

public final class ActivityManager {

    private static ActivityManager mInstance;
    private static final Map<String, List<Activity>> mCollector = new ConcurrentHashMap<>();

    public static final String KEY_FINANCE_FROM_MAIN = UUID.randomUUID().toString();
    public static final String KEY_FINANCE_FROM_LIST = UUID.randomUUID().toString();

    private ActivityManager() {
    }

    public static ActivityManager getInstance() {
        if (mInstance == null) {
            synchronized (ActivityManager.class) {
                if (mInstance == null)
                    mInstance = new ActivityManager();
            }
        }
        return mInstance;
    }

    public void addActivity(String key, Activity activity) {
        List<Activity> activities = mCollector.get(key);
        if (activities == null)
            activities = new ArrayList<>();
        if (!activities.contains(activity))
            activities.add(activity);
        mCollector.put(key, activities);
    }

    public void removeActivity(String key, Activity activity) {
        List<Activity> activities = mCollector.get(key);
        if (activities == null) return;
        activities.remove(activity);
        mCollector.put(key, activities);
    }

    public void finishActivities(String key) {
        List<Activity> activities = mCollector.get(key);
        if (activities == null) return;
        for (Activity activity : activities) {
            if (activity == null) continue;
            if (activity.isFinishing()) continue;
            activity.finish();
        }
    }
}
